// var Util = require('../../utils/util.js')
// var Http = require('../../utils/http.js')
// var Session = require('../../utils/session.js')
// var DeviceModel = require('../../model/device_model.js')
// var CommandModel = require('../../model/command_model.js')
// let Toast = require('../../utils/toast.js')
// var Comm = require('../../utils/comm.js')

// pages/recipesDetail-2.0.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    default_banner: "https://ai-cdn.joyoung.com/ia/images/soymilk/banner.jpg",
    applicable_model: "无人破壁豆浆机K8，K61。破壁料理机XX",
    content: "食谱故事食谱故事食谱故事食谱故事",
    icon_like_comment: "https://ai-cdn.joyoung.com/ia/images/soymilk/icon_like_comment.png",
    user_header_item: "https://ai-cdn.joyoung.com/ia/images/soymilk/default_avator.png",
    icon_add_equip: "https://ai-cdn.joyoung.com/ia/images/soymilk/icon_add_equip.png",
    // screenHeight: app.globalData.systemInfo.screenHeight,
    // screenWidth: app.globalData.systemInfo.screenWidth,
    // windowHeight: app.globalData.systemInfo.windowHeight,
    // kMarginTop: app.globalData.navigationBarHeight,
    // kStoreAppId: app.globalData.storeAppId,
    // storePageUrl: app.globalData.storePath,
    loopTimer: null,
    ctrlDev: null,
    workingName: '',
    tapEnable: true, //功能是否可以点击
    isStartViewShow: false, //控制操作食谱是否显示
    isReservationViewShow: false, //预约视图是否显示
    defaultCapacity: 0,
    capacityList: [],
    timeValue: '',
    startType: '开始制作',
    startText: '开始烹饪',
    typeCode: 1,
    preViewType: 0, // 0 制作， 1预约
    validCtrlDevList: [],
    mutableDevices: [],
    devIndex: 0,
    stackLevel: 1,
    cancelSecond: 0,
    cancelTimer: null,
    canCountDown: true,
    pop_back: "https://ai-cdn.joyoung.com/ia/images/soymilk/icon_pop_back.png",
    isNoDev: false,
    tasteList: ['标准', '香郁'],
    tasteCode: 0, //口感值  0 标准  1 香郁
    offlineToast: true,
    equipmentModel: 1,//设备型号 0 豆浆机 1 饭煲
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this

    var mId = options.menuId
    if (options.q) {
      // 来自微信扫一扫
      var url = decodeURIComponent(options.q)
      var menuId = Util.getQueryVariable(url, 'r')
      mId = menuId
    }

    var devId = options.devId

    // 请求食谱详情
    var param = {
      'menu_id': mId
    }

    // 缓存的Key
    this.data.capacityCacheKey = 'KEY_MENU_CAPACITY_' + mId
    var cacheKey = 'DETAIL_CACHE_KEY_' + mId
    var resp = Session.value(cacheKey)
    if (resp) {
      dealMenuInfo(resp)
    }

    wx.showLoading()
    Http.menuDetail(param, function(resp) {
      wx.hideLoading()
      if (resp.code == 0) {
        Session.setValue(cacheKey, resp)
        dealMenuInfo(resp)

        var applicableModel = resp.data.applicable_model
        // 获取设备列表
        getDevList(devId, applicableModel)
      } else {
        that.setData({
          hasDetail: false
        })
      }
    })

    // 获取层级
    var level = 1
    if (Util.currentPageStack() == 1) {
      level = 2
    }
    that.setData({
      stackLevel: level,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //循环查询设备状态
    this.data.loopTimer = setInterval(this.getCurrentDevInfo, 5000)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var that = this
    app.globalData.workCancelSecond = that.data.cancelSecond
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this
    app.globalData.workCancelSecond = that.data.cancelSecond
    clearInterval(that.data.loopTimer)
    clearInterval(that.data.cancelTimer)
    this.setData({
      loopTimer: null,
      cancelTimer: null,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  onShareAppMessage: function() {

    var that = this;
    var tempMenuItem = that.data.menuItem

    return {
      title: tempMenuItem.mname,
      path: '/pages/recipesDetail-2.0/recipesDetail-2.0?menuId=' + tempMenuItem.menu_id,
      imageUrl: tempMenuItem.img_url,
      success: function(resp) {
        //转发成功
        console.log('分享成功___' + resp)
        requestAddUserShareIntegral()
      },
      fail: function(resp) {
        //转发失败
        console.log('分享失败___' + resp)
      }
    }

  },

  /***********************Event***************************/
  /**
   * 扫描二维码
   */
  scanMenuQRCode: function(para) {
    var that = this
    var formId = para.detail.formId
    wx.scanCode({
      success: (res) => {
        var url = res.result
        var sncode = Util.getQueryVariable(url, 'p')
        console.log(sncode)
        if (Session.isLogin()) {
          if (sncode) {
            //调整到首页，并且绑定设备
            wx.reLaunch({
              url: '/pages/index/index?formId=' + formId + '&snCode=' + sncode,
            })

          } else {
            Toast.toastFail('无效的二维码')
          }
        } else {
          //保存sncode
          if (sncode) {
            Session.setValue('sncode', sncode)
            //跳转到登录
            wx.reLaunch({
              url: '/pages/login/login',
            })
          } else {
            Toast.toastFail('无效的二维码')
          }
        }
      }
    })
  },

  //预约
  reserveTap: function() {
    var that = this
    var validCtrlDevList = that.data.validCtrlDevList
    if (!that.data.ctrlDev) {
      if (validCtrlDevList.length == 1) {
        that.setData({
          ctrlDev: validCtrlDevList[0],
        })
      }
    }

    if (this.data.errorCount > 2) {
      this.setData({
        tapEnable: true,
        errorCount: 0
      })
    } else {
      var count = this.data.errorCount
      this.setData({
        errorCount: count + 1
      })
    }

    if (!this.data.tapEnable || app.globalData.cancelCount >= 5) {
      Toast.toastFail('请稍后再操作')
      return
    }

    if (this.data.ctrlDev.onlineStatus == '离线') {
      Toast.toastFail('设备已离线')
    } else {

      infoOfCapacity()

      var time = Util.dateAfterMin(30)
      this.setData({
        isStartViewShow: true,
        over_time: true,
        timeValue: time,
        reservationTime: {
          'hour': '0',
          'min': '30'
        },
        preViewType: 1,
        startType: '确认预约',
        typeCode: 2,
        tasteCode: 0,
      })
    }
  },

  pickerViewValueChange: function(e) {
    var enable = e.detail.enable
    var time = 0
    var code = 1
    var opType = '开始制作'
    if (enable) {
      var value = e.detail.time
      if (value) {
        time = Util.timeDifference(value)
        this.setData({
          timeValue: value,
        })
      }

      opType = '确认预约'
      code = 2
    }

    this.setData({
      reservationTime: time,
      startType: opType,
      typeCode: code,
    })
  },

  pickerViewValueChangeA: function(e) {
      var enable = e.detail.enable
      var time = {
          'hour': '0',
          'min': '30'
      }
      var code = 1
      var opType = '开始烹饪'
      var isReserVation = 0
      if (enable) {
          var value = e.detail.time
          if (value) {
              time = Util.timeDifference(value)
              this.setData({
                  timeValue: value,
              })
          }

          opType = '开始预约'
          code = 2
          isReserVation = 1
      }

      this.setData({
          reservationTime: time,
          startText: opType,
          startType: code,
          preViewType: isReserVation
      })
    },

  /**
   * 控制参数食谱图
   */
  closeOPView: function() {
    this.setData({
      isStartViewShow: false,
      isReservationViewShow: false,
      capacity: '500'
    })
  },

  startTap: function() {
    var that = this
    var validCtrlDevList = that.data.validCtrlDevList
    if (!that.data.ctrlDev) {
      if (validCtrlDevList.length == 1) {
        that.setData({
          ctrlDev: validCtrlDevList[0],
        })
      }
    }

    if (this.data.errorCount > 2) {
      this.setData({
        tapEnable: true,
        errorCount: 0
      })
    } else {
      var count = this.data.errorCount
      this.setData({
        errorCount: count + 1
      })
    }

    if (!this.data.tapEnable || app.globalData.cancelCount >= 5) {
      Toast.toastFail('请稍后再操作')
      return
    }

    if (this.data.ctrlDev.onlineStatus == '离线') {
      Toast.toastFail('设备已离线')
    } else {
      infoOfCapacity()

      var time = Util.dateAfterMin(30)
      this.setData({
        isStartViewShow: true,
        over_time: false,
        timeValue: time,
        reservationTime: {
          'hour': '0',
          'min': '0'
        },
        preViewType: 0,
        startType: '开始制作',
        typeCode: 1,
        tasteCode: 0,
      })
    }
  },

  tasteValueChange: function(e) {
    var that = this
    var text = e.detail.item.text
    var code = 0
    if (text == '标准') {
      code = 0
    } else {
      code = 1
    }
    that.setData({
      tasteCode: code
    })
  },

  /**
   * 选项值改变
   */
  checkBoxValueChange: function(e) {
    var text = e.detail.item.text
    var detail = detailWithCapacity(text)
    this.setData({
      capacity: text,
      customer: detail.customer,
      capacityCode: detail.code,
      norm: detail.norm,
    })
  },

  // 制作/预约食谱
  cookMenu: function(e) {
    var that = this
    var ctrlType = e.currentTarget.dataset.ctrltype
    var dev = this.data.ctrlDev
    if (ctrlType != 0) {
      if (!app.globalData.opTimer) {
        app.beginCountDown()
      }

      that.data.canCountDown = true
      var second = 60
      if (dev.mdcode == 14) {
        second = 30
      }
      that.setData({
        cancelSecond: second,
      })
    } else {
      app.globalData.cancelCount += 1
    }

    //发送启动
    var param = {
      'devId': dev.did,
      'ctrType': ctrlType
    }
    if (ctrlType == 1 || ctrlType == 2) {
      var modelList = this.data.menuItem.model_list
      var model
      for(var idx in modelList){
        var m = modelList[idx]
        if (m.dcode == dev.mdcode){
          model = m
          break
        }
      }
      var menuCode = model.menucode
      var capacityCode = this.data.capacityCode
      var capacityText = this.data.capacity

      param.isCloud = 1
      param.menuCode = menuCode
      param.capacity = capacityCode
      param.orderTime = 0
      var params = model.params
      for (var index in params) {
        var cmd = params[index]
        if (cmd.p_name == capacityText) {
          var taste = that.data.tasteCode
          var content = cmd.p_value
          if (taste == 1) {
            content = cmd.p_value2
          }
          param.menuContent = cmd.p_value
        }
      }

      if (ctrlType == 2) {
        var time = this.data.reservationTime
        var min = parseInt(time.hour) * 60 + parseInt(time.min)
        param.orderTime = min
      }

      // 启动
      this.setData({
        tapEnable: false
      })
    }
    wx.showLoading()
    Http.ctrlDev(param, function(resp) {
      wx.hideLoading()
    })

    // 更新默认容量
    if (ctrlType != 0) {
      var cachekey = this.data.capacityCacheKey
      var cacheValue = this.data.capacity
      Session.setValue(cachekey, cacheValue)
    } else {
      // 停止计时
      clearInterval(that.data.cancelTimer)
      app.globalData.workCancelSecond = 0
      that.setData({
        cancelTimer: null,
      })
    }

    // 延迟2秒后查询设备状态
    setTimeout(function() {
      getDevInfo(dev, function(resp) {
        if (dev.workStatus != 0 && dev.workStatus != 1) {
          that.setData({
            tapEnable: true
          })
        }

        wx.hideLoading()
        if (resp.code == 0) {
          Toast.toastSuccess('操作成功')
        }
        that.setData({
          isStartViewShow: false,
          isReservationViewShow: false,
          capacity: '500'
        })
      })

    }, 2500)
  },

  // 获取设备状态
  getCurrentDevInfo: function() {
    var that = this
    var dev = that.data.ctrlDev
    if (dev) {
      getDevInfo(dev, function(resp) {
        if (dev.workStatus != 0 && dev.workStatus != 1) {
          that.setData({
            tapEnable: true,
            isStartViewShow: false,
            isReservationViewShow: false,
          })
        }

        // 根据功能编号获取工作的食谱编码
        var localList = Session.value('KEY_LOCAL_MENU_LIST')
        var tList = localList[0]
        for (var idx = 1; idx < localList.length; idx++) {
          var list = localList[idx]
          tList = tList.concat(list)
        }
        var tempName = ''
        if (dev.func == 114 || dev.func == 115) {
          tempName = '自动清洗'
        }

        for (var idx in tList) {
          var item = tList[idx]
          if (item.menucode == dev.func) {
            tempName = item.name
            break
          }
        }

        var canCountDown = that.data.canCountDown
        var s = dev.canCancelTime
        if (s > 0 && canCountDown && dev.workStatus != 14) {
          that.data.canCountDown = false
          if (s > app.globalData.workCancelSecond && app.globalData.workCancelSecond != 0) {
            s = app.globalData.workCancelSecond
          }
          benginCanCelCountDown(s)
        } else if (dev.workStatus == 14 && s > 0){
          // 报异常了 并且处于可取消状态
          that.data.canCountDown = true
          clearInterval(that.data.cancelTimer)
          app.globalData.workCancelSecond = 0
          that.setData({
            cancelTimer: null,
          })
        }

        that.setData({
          ctrlDev: dev,
          workingName: tempName,
        })
      })
    }
  },

  // 料包购买
  foodstore: function() {
    gotoStore()
  },

  // 预约选择设备
  pickerChangeDevice: function(e) {
    var that = this
    var index = e.detail.value
    var dev = that.data.validCtrlDevList[index]
    that.setData({
      ctrlDev: dev
    })

    var ctrlType = e.currentTarget.dataset.ctrltype
    if (ctrlType == 1) {
      // 制作
      that.startTap()
    } else {
      // 预约
      that.reserveTap()
    }
  },

  /**
   * 加载首页
   */
  goHome: function() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
})

/*************************************************************************************************/
function getDevInfo(dev, callback) {
  var that = Util.weakSelf()
  if (dev) {
    var data = {
      'devId': dev.did
    }
    Http.devInfo(data, function(resp) {
      if (resp.code == 0) {
        var data = resp.data
        if (!data) {
          data = resp
        }

        if (!that.data.offlineToast) {
          that.setData({
            offlineToast: true
          })
        }

        //将收到的信息转化为状态Model
        let comm = CommandModel.initCommand(data)
        //更新设备状态
        dev.updateDevWorkStatus(comm)
        typeof callback == 'function' && callback(data)
      } else if (resp.code == 10015 && that.data.offlineToast) {
        wx.hideLoading()
        dev.devOffline()

        that.setData({
          offlineToast: false,
          isReservationViewShow: false,
          isStartViewShow: false,
          ctrlDev: dev,
        })
        wx.showModal({
          title: '提示',
          content: resp.msg,
          showCancel: false
        })
      }
    })
  }
}

function dealMenuInfo(resp) {
  var that = Util.weakSelf()

  var item = resp.data
  // 步骤
  var byways = item.byways
  for (var index in byways) {
    var dict = byways[index]
    var stepNo = parseInt(dict.seq)
    dict.step = stepNo + 1
    byways[index] = dict
  }
  item.byways = byways

  // 料包名
  var materials = item.shop_materials
  var materialName = ''
  if (materials.length > 0) {
    materialName = materials[0].name
  }

  that.setData({
    menuItem: item,
    materialName: materialName,
    detailParams: item.model_list,
  })
  that.getCurrentDevInfo()

  wx.showShareMenu()
}

function infoOfCapacity() {
  var that = Util.weakSelf()
  var detailParams = that.data.detailParams
  var currentDcode = that.data.ctrlDev.mdcode
  var item = that.data.menuItem

  var cList = []
  var params = []

  for (var idx in detailParams) {
    var modelList = detailParams[idx]
    if (modelList.dcode == currentDcode) {
      params = modelList.params
      item.menuTaste = menuTaste(params)

      for (var index in params) {
        var dict = params[index]
        var cType = dict.p_name
        cList.push(cType)
      }
      cList.sort(Util.numAscSort)
      break
    }
  }

  var isDefault = 0
  var text = '800'
  var detail = {}
  for (var idx in params) {
    var dict = params[idx]
    if (dict.p_isdefault == '1') {
      text = dict.p_name
      isDefault = cList.indexOf(text)
      detail = detailWithCapacity(text)
      break
    }
  }

  var cachekey = that.data.capacityCacheKey
  var cacheValue = Session.value(cachekey, cacheValue)
  if (cacheValue != '') {
    for (var idx in params) {
      var dict = params[idx]
      if (dict.p_name == cacheValue) {
        text = dict.p_name
        isDefault = cList.indexOf(text)
        detail = detailWithCapacity(text)
        break
      }
    }
  }

  that.setData({
    defaultCapacity: isDefault,
    customer: detail.customer,
    capacityCode: detail.code,
    capacity: text,
    norm: detail.norm,
    capacityList: cList,
    menuItem: item,
  })
}

function detailWithCapacity(capacity) {
  var result = {
    'customer': '1',
    'code': 0,
    'norm': '20'
  }
  if (capacity == '300' || capacity == '400') {
    result.customer = '1'
    result.code = 1
    result.norm = '20'
  } else if (capacity == '500' || capacity == '600') {
    result.customer = '1~2'
    result.code = 2
    result.norm = '40'
  } else if (capacity == '800') {
    result.customer = '2~3'
    result.code = 3
    result.norm = '60'
  } else if (capacity == '1000') {
    result.customer = '3~4'
    result.code = 4
    result.norm = '60'
  }
  return result
}

/**
 * 获取设备列表
 */
function getDevList(devId, applicableModel) {
  var that = Util.weakSelf()
  if (Session.isLogin()) {
    Comm.devList(function(devList) {
      var currentDev = null
      var validDevList = []
      var devNames = []
      for (var idx in devList) {
        var dev = devList[idx]
        var index = applicableModel.indexOf(dev.mname)
        if (index > -1 && dev.isonline == 1) {
          //在线的可以控制的设备
          validDevList.push(dev)
          devNames.push(dev.dname)
        }
        if (devId == dev.did) {
          // 当前控制的设备
          currentDev = dev
          break
        }
      }

      if (!currentDev) {
        if (validDevList.length == 1) {
          currentDev = validDevList[0]
        }
      } else {
        validDevList = []
      }

      var noDev = false
      if (!currentDev && validDevList.length <= 0) {
        noDev = true
      }

      that.setData({
        validCtrlDevList: validDevList,
        ctrlDev: currentDev,
        mutableDevices: devNames,
        isNoDev: noDev,
      })
      that.getCurrentDevInfo()
    })
  }
}


/**
 * 用户分享添加积分的接口
 */
function requestAddUserShareIntegral() {

  var that = Util.weakSelf()
  var tempMenuItem = that.data.menuItem

  var prams = {
    "condition_object": tempMenuItem.menu_id,
    "record_info": tempMenuItem.mname,
    "record_source_type": "QYJXCXD",
    "rule_code": "QYJ009",
    "source_code": "4",
  }
  Http.addUserIntegral(prams, function(resp) {
    if (resp.code == 0) {

    }
  })
}

function benginCanCelCountDown(time) {
  var that = Util.weakSelf()
  that.data.cancelTimer = Util.countDownTimer(time, function(second) {
    if (second >= 0) {
      that.setData({
        cancelSecond: second
      })
    } else {
      clearInterval(that.data.cancelTimer)
    }
  })
}



/**
 * 跳转到商城
 */
function gotoStore() {
  var that = Util.weakSelf()
  var appId = that.data.kStoreAppId
  var path = that.data.storePageUrl
  wx.navigateToMiniProgram({
    appId: appId,
    path: path,
    success(res) {
      // 打开成功
      //1.添加积分
      requestAddUserIntegralFromLookStore()

      //2.访问商城记录
      requestAddProgramJumpLog()
    }
  })
}


/**
 * 用户跳转商城添加积分的接口
 */
function requestAddUserIntegralFromLookStore() {
  var that = Util.weakSelf()

  var appId = that.data.kStoreAppId
  // var path = that.data.storePageUrl

  var prams = {
    "condition_object": appId,
    "record_info": "商品",
    "record_source_type": "QYJXCXD",
    "rule_code": "QYJ010",
    "source_code": "4",
  }
  Http.addUserIntegral(prams, function(resp) {
    if (resp.code == 0) {

    }
  })
}

/**
 * 商城跳转记录
 */
function requestAddProgramJumpLog() {
  var that = Util.weakSelf()

  var appId = that.data.kStoreAppId
  var path = that.data.storePageUrl

  var prams = {
    "mini_program_id": appId,
    "page_url": path,
  }
  Http.addProgramJumpLog(prams, function(resp) {
    if (resp.code == 0) {

    }
  })
}

function menuTaste(paramList) {
  var result = false
  for (var idx in paramList) {
    var param = paramList[idx]
    if (param.p_value2 != undefined) {
      result = true
      break
    }
  }
  return result
}